<?php
/**
 * Created By PhpStorm
 * Author: patrick wu
 * Date: 2020/10/12
 * Time: 17:49
 */
namespace App\Http\Model\Mysql;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;

class UserCouponModel extends Model
{
    const SELF_FETCH    =   1,      //手动领取
        SYSTEM_FETCH    =   2;      //系统派送

    const IS_EXPIRE     =   1,      //已过期
        NOT_EXPIRE      =   0;      //未过期

    const IS_USE        =   1,      //已使用
        NOT_USE         =   0;      //未使用

    const IS_DELETE     =   1,      //已删除
        NOT_DELETE      =   0;      //未删除

    protected $table    =   'mini_user_coupon';

    protected $guarded  =   [];

    protected $dateFormat   =   'U';

    /**
     * 选取用户有用的优惠券
     * @param $query
     * @param $user_id
     */
    public function scopeUseful($query, $user_id)
    {
        $query->where(['user_id' => $user_id, 'is_use' => self::NOT_USE, 'is_delete' => self::NOT_DELETE])->where('begin_time', '<=', Carbon::now()->timestamp)->where('end_time', '>=', Carbon::now()->timestamp);
    }

    /**
     * 定义链接优惠券表
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function coupon()
    {
        return $this->hasOne(CouponModel::class, 'id', 'coupon_id');
    }
}
